﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using dal.cgm_production_dao;
using FastReport.Utils;
using Newtonsoft.Json;
using utils;
using static System.Net.Mime.MediaTypeNames;

namespace local_label_printing
{
    public partial class Form1 : Form
    {
        string frxName = "inner_label.frx";


        public Form1()
        {
            InitializeComponent();
            SetPlaceholderText(productionDateTextBox, "yyMMdd");
            SetPlaceholderText(expireTextBox, "yyMMdd");

         

            // 绑定事件
            productionDateTextBox.Enter += new EventHandler(productionDateTextBox_Enter);
            productionDateTextBox.Leave += new EventHandler(productionDateTextBox_Leave);
            expireTextBox.Enter += new EventHandler(expireDateTextBox_Enter);
            expireTextBox.Leave += new EventHandler(expireDateTextBox_Leave);

            versionLabel.Text = "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            listBox1.Text = "内包装标签";



        }

        private void onListValueChange(object sender, EventArgs e)
        {
            var text = listBox1.Text;

            gtinLabel.Visible= false;
            gtinTextBox.Visible= false;

            operatorLabel.Visible = false;
            operatorTextBox.Visible = false;

            macLabel.Visible = false;
            macTextBox.Visible = false;

            productionLabel.Visible = false;
            productionDateTextBox.Visible = false;

            expireLabel.Visible = false;
            expireTextBox.Visible = false;

            batchLabel.Visible = false;
            batchTextBox.Visible = false;

            snLabel.Visible = false;
            snTextBox.Visible = false;

            countLabel.Visible = false;
            countTextBox.Visible = false;
           

            if (text == "内包装标签")
            {
                gtinLabel.Visible = true;
                gtinTextBox.Visible = true;
                gtinTextBox.Text = "06930251802174";

                productionLabel.Visible = true;
                productionDateTextBox.Visible = true;

                expireLabel.Visible = true;
                expireTextBox.Visible = true;

                batchLabel.Visible = true;
                batchTextBox.Visible = true;

                snLabel.Visible = true;
                snTextBox.Visible = true;

                countTextBox.Visible = true;
                countLabel.Visible = true;

                frxName = "inner_label.frx";
            }
            else if (text == "彩盒标签")
            {
                gtinLabel.Visible = true;
                gtinTextBox.Visible = true;
                gtinTextBox.Text = "16930251802171";


                operatorLabel.Visible = true;
                operatorTextBox.Visible = true;

                productionLabel.Visible = true;
                productionDateTextBox.Visible = true;

                expireLabel.Visible = true;
                expireTextBox.Visible = true;

                batchLabel.Visible = true;
                batchTextBox.Visible = true;

                snLabel.Visible = true;
                snTextBox.Visible = true;

                countTextBox.Visible = true;
                countLabel.Visible = true;

                frxName = "color_box_label.frx";


            }
            else if (text == "外箱标签")
            {

                gtinLabel.Visible = true;
                gtinTextBox.Visible = true;
                gtinTextBox.Text = "26930251802178";

                productionLabel.Visible = true;
                productionDateTextBox.Visible = true;

                expireLabel.Visible = true;
                expireTextBox.Visible = true;

                batchLabel.Visible = true;
                batchTextBox.Visible = true;

                frxName = "outerbox_label.frx";


            }
            else if (text == "内包装标签（英文）")
            {

                gtinLabel.Visible = true;
                gtinTextBox.Visible = true;
                gtinTextBox.Text = "08500441188852";

                productionLabel.Visible = true;
                productionDateTextBox.Visible = true;

                expireLabel.Visible = true;
                expireTextBox.Visible = true;

                batchLabel.Visible = true;
                batchTextBox.Visible = true;

                snLabel.Visible = true;
                snTextBox.Visible = true;

                countTextBox.Visible = true;
                countLabel.Visible = true;

                frxName = "inner_label_en.frx";



            }
            else if (text == "彩盒标签（英文）")
            {

                gtinLabel.Visible = true;
                gtinTextBox.Visible = true;
                gtinTextBox.Text = "18500441188859";

                productionLabel.Visible = true;
                productionDateTextBox.Visible = true;

                expireLabel.Visible = true;
                expireTextBox.Visible = true;

                batchLabel.Visible = true;
                batchTextBox.Visible = true;

                snLabel.Visible = true;
                snTextBox.Visible = true;

                countTextBox.Visible = true;
                countLabel.Visible = true;

                frxName = "color_box_label_en.frx";



            }
            else if (text == "外箱标签（英文）")
            {

                gtinLabel.Visible = true;
                gtinTextBox.Visible = true;
                gtinTextBox.Text = "28500441188856";

                productionLabel.Visible = true;
                productionDateTextBox.Visible = true;

                expireLabel.Visible = true;
                expireTextBox.Visible = true;

                batchLabel.Visible = true;
                batchTextBox.Visible = true;

                frxName = "outerbox_label_en.frx";


            }
            else if (text == "接收器铭牌")
            {
                productionLabel.Visible = true;
                productionDateTextBox.Visible = true;

                batchLabel.Visible = true;
                batchTextBox.Visible = true;

                snLabel.Visible = true;
                snTextBox.Visible = true;

                countTextBox.Visible = true;
                countLabel.Visible = true;

                frxName = "reader_label.frx";


            }
            else if (text == "接收器彩盒标签")
            {

                gtinLabel.Visible = true;
                gtinTextBox.Visible = true;
                gtinTextBox.Text = "08500441188784";

                productionLabel.Visible = true;
                productionDateTextBox.Visible = true;

                batchLabel.Visible = true;
                batchTextBox.Visible = true;

                snLabel.Visible = true;
                snTextBox.Visible = true;

                countTextBox.Visible = true;
                countLabel.Visible = true;

                frxName = "reader_color_box_label.frx";



            }
            else if (text == "接收器外箱标签")
            {

                gtinLabel.Visible = true;
                gtinTextBox.Visible = true;
                gtinTextBox.Text = "18500441188781";

                productionLabel.Visible = true;
                productionDateTextBox.Visible = true;

                batchLabel.Visible = true;
                batchTextBox.Visible = true;

                frxName = "reader_outerbox_label.frx";


            }
            else if (text == "转运标签")
            {
                macLabel.Visible = true;
                macTextBox.Visible = true;

                frxName = "transport_label.frx";

            }
            else if (text == "助针器标签")
            {
                macLabel.Visible = true ;
                macTextBox.Visible = true;

                productionLabel.Visible = true;
                productionDateTextBox.Visible = true;

                expireLabel.Visible = true;
                expireTextBox.Visible = true;

                frxName = "applicator_label.frx";

            }
           
        }
        private void SetPlaceholderText(TextBox textBox, string placeholderText)
        {
            textBox.Text = placeholderText;
            textBox.ForeColor = Color.Gray;
        }
        // 恢复正常文本颜色
        private void RemovePlaceholderText(TextBox textBox)
        {
            textBox.ForeColor = Color.Black;
        }
        // productionDateTextBox 进入事件
        private void productionDateTextBox_Enter(object sender, EventArgs e)
        {
            if(productionDateTextBox.Text != "yyMMdd")
            {
                return;
            }
            SetPlaceholderText(productionDateTextBox, "yyMMdd");
            {
                productionDateTextBox.Text = "";
                RemovePlaceholderText(productionDateTextBox);
            }
        }
        // productionDateTextBox 离开事件
        private void productionDateTextBox_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(productionDateTextBox.Text))
            {
                SetPlaceholderText(productionDateTextBox, "yyMMdd");
            }
        }

        private void expireDateTextBox_Enter(object sender, EventArgs e)
        {
            if (expireTextBox.Text != "yyMMdd")
            {
                return;
            }
            SetPlaceholderText(expireTextBox, "yyMMdd");
            {
                expireTextBox.Text = "";
                RemovePlaceholderText(expireTextBox);
            }
        }
        // productionDateTextBox 离开事件
        private void expireDateTextBox_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(expireTextBox .Text))
            {
                SetPlaceholderText(expireTextBox, "yyMMdd");
            }
        }



        /// <summary>
        /// HandleError
        /// </summary>
        /// <param name="message"></param>
        private void HandleError(string message)
        {
            
            AppendLog($"{message}", false);
            ApiLog.Debug($"{message}");

        }


        /// <summary>
        /// AppendLog
        /// </summary>
        /// <param name="message"></param>
        /// <param name="isError"></param>
        private void AppendLog(string message, bool isError)
        {
            // 选择文本颜色
            Color textColor = isError ? Color.Black : Color.Red;

            // 设置光标位置并插入文本
            logRichTextBox.SelectionStart = logRichTextBox.TextLength;
            logRichTextBox.SelectionLength = 0; // 取消任何选择

            logRichTextBox.SelectionColor = textColor; // 设置颜色
            logRichTextBox.AppendText(message + "\n"); // 添加文本
            logRichTextBox.SelectionColor = logRichTextBox.ForeColor; // 恢复默认颜色
            logRichTextBox.ScrollToCaret(); // 自动滚动到最后
        }

        /// <summary>
        /// 清空日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearLogButton_Click(object sender, EventArgs e)
        {
            logRichTextBox.Clear();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            //参数校验

            if (gtinTextBox.Visible)
            {
                //产品标识校验
                string text = gtinTextBox.Text.Trim();
                if (!Regex.IsMatch(text, "^[0-9]{14}$"))
                {
                    HandleError("产品标识格式校验失败");
                    return;
                }

            }

            if (operatorTextBox.Visible)
            {
                //操作员校验
                string text = operatorTextBox.Text.Trim();
                if (!Regex.IsMatch(text, "^[0-9]{2}$"))
                {
                    HandleError("操作员格式校验失败");
                    return;
                }
            }


            if (macTextBox.Visible)
            {
                //MAC校验
                string text = macTextBox.Text.Trim();
                if (!Regex.IsMatch(text, "^[0-9A-Z]{12}$"))
                {
                    HandleError("MAC格式校验失败");
                    return;
                }
            }

            if (productionDateTextBox.Visible)
            {
                //生产日期校验
                string text = productionDateTextBox.Text.Trim();
                if (text == "yyMMdd" || !Regex.IsMatch(text, "^[0-9]{6}$"))
                {
                    HandleError("生产日期格式校验失败");
                    return;
                }
            }

            if (expireTextBox.Visible)
            {
                //过期日期校验
                string text = expireTextBox.Text.Trim();
                if (text == "yyMMdd"  ||  !Regex.IsMatch(text, "^[0-9]{6}$"))
                {
                    HandleError("过期日期格式校验失败");
                    return;
                }
            }

            if (batchTextBox.Visible)
            {
                //生产批号校验
                string text = batchTextBox.Text.Trim();
                if (!Regex.IsMatch(text, @"^\d{2}[A-Z]\d{7}$"))
                {
                    HandleError("生产批号格式校验失败");
                    return;
                }

           
            }

            if (snTextBox.Visible)
            {
                string text = snTextBox.Text.Trim();

                int count = int.Parse(countTextBox.Text.Trim());

                if (count <= 0) {
                    HandleError("打印张数不能为0");
                    return;
                }
                string[] snList = new string[count];
                    
                //序列号校验
                if (listBox1.Text.Contains("接收器"))
                {
                    //接收器
                    if (!Regex.IsMatch(text, @"^[0-9A-Za-z]{3}\d{6}$"))
                    {
                        HandleError("接收器序列号格式校验失败");
                        return;
                    }
                    try
                    {
                        int startSN = int.Parse(snTextBox.Text.Substring(text.Length - 5, 5));

                        if (startSN == 0)
                        {
                            MessageBox.Show("请输入正确格式序列号，起始序列号需大于0", "序列号格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        if (count + startSN - 1 > 99999)
                        {
                            MessageBox.Show("请输正确入打印张数,最后一张序列号大于99999", "打印张数错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        string snPrefix = text.Substring(0, 4);
                        for (int i = 0; i < count; i++)
                        {
                            snList[i] = snPrefix + (startSN + i).ToString();
                        }
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show("请输入正确的序列号", "序列号格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                else
                {
                    //助针器
                    if (!Regex.IsMatch(text, @"^[0-9A-Za-z]{10}$"))
                    {
                        HandleError("助针器序列号格式校验失败");
                        return;
                    }

                    try
                    {
                        UInt16 startSN = Convert.ToUInt16(text.Substring(text.Length - 3, 3), 16);

                        if (startSN == 0)
                        {
                            MessageBox.Show("请输入正确格式序列号，起始序列号需大于0", "序列号格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        if (count + startSN - 1 > 0xfff)
                        {
                            MessageBox.Show("请输正确入打印张数,最后一张序列号大于0xfff", "打印张数错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        string snPrefix = text.Substring(0, 7);
                        for (int i = 0; i < count; i++)
                        {
                            snList[i] = snPrefix + (startSN + i).ToString("X3");
                        }
                    
                    }
                    catch (Exception ex) {
                        MessageBox.Show("请输入正确的序列号", "序列号格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                }

                for (int i = 0; i < count; i++)
                {
                    try
                    {
                        var reportPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, frxName);
                        FastReport.Report report = new FastReport.Report();
                        report.Load(reportPath);

                        var model = new
                        {
                            ProductionCode = gtinTextBox.Text,
                            ProductionDate = productionDateTextBox.Text,
                            ExpiryDate = expireTextBox.Text,
                            ProductionBatch = batchTextBox.Text,
                            SerialCode = snList[i],
                            OperatorCode = operatorTextBox.Text.Trim(),
                            Mac = macTextBox.Text,
                            EightChars = macTextBox.Text.Length >= 6 ? macTextBox.Text.Substring(macTextBox.Text.Length - 6) : macTextBox.Text
                        };

                        //刷选可以打印字段特性的模型属性
                        var list = model.GetType().GetProperties();
                        //批量设置打印模板参数值
                        foreach (PropertyInfo pro in list)
                        {
                            var value = pro.GetValue(model, null);
                            //获取参数
                            FastReport.Data.Parameter param = report.Parameters.FindByName(pro.Name);
                            if (param != null)
                            {

                                param.Value = value; //将属性的值赋值给名字相同的报表参数
                            }
                        }
                        report.PrintSettings.Printer = "ZDesigner ZT510-300dpi ZPL"; // 设置默认打印机
                        report.PrintSettings.ShowDialog = false; // 禁止显示打印对话框
                        report.Prepare();
                        if (checkViewPrint.Checked)
                        {
                            if (i == 0)
                            {
                                report.ShowPrepared();
                            }
                       
                        }
                        else
                        {
                            // 直接打印报表
                            report.Print();
                        }


                        // 释放使用的资源
                        report.Dispose();

                    }
                    catch (Exception ex)
                    {
                        HandleError(ex.Message);
                    }

                }
            }
            else
            {
                try
                {
                    var reportPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, frxName);
                    FastReport.Report report = new FastReport.Report();
                    report.Load(reportPath);

                    var model = new
                    {
                        ProductionCode = gtinTextBox.Text,
                        ProductionDate = productionDateTextBox.Text,
                        ExpiryDate = expireTextBox.Text,
                        ProductionBatch = batchTextBox.Text,
                        SerialCode = snTextBox.Text,
                        OperatorCode = operatorTextBox.Text.Trim(),
                        Mac = macTextBox.Text,
                        EightChars = macTextBox.Text.Length >= 6 ? macTextBox.Text.Substring(macTextBox.Text.Length - 6) : macTextBox.Text
                    };

                    //刷选可以打印字段特性的模型属性
                    var list = model.GetType().GetProperties();
                    //批量设置打印模板参数值
                    foreach (PropertyInfo pro in list)
                    {
                        var value = pro.GetValue(model, null);
                        //获取参数
                        FastReport.Data.Parameter param = report.Parameters.FindByName(pro.Name);
                        if (param != null)
                        {

                            param.Value = value; //将属性的值赋值给名字相同的报表参数
                        }
                    }
                    report.PrintSettings.Printer = "ZDesigner ZT510-300dpi ZPL"; // 设置默认打印机
                    report.PrintSettings.ShowDialog = false; // 禁止显示打印对话框
                    report.Prepare();
                    if (checkViewPrint.Checked)
                    {
                        report.ShowPrepared();
                    }
                    else
                    {
                        // 直接打印报表
                        report.Print();
                    }


                    // 释放使用的资源
                    report.Dispose();

                }
                catch (Exception ex)
                {
                    HandleError(ex.Message);
                }
            }
          
           


           
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void macLabel_Click(object sender, EventArgs e)
        {

        }
    }
}
